import Field from './field';
import Validator from './../core/validate';
import {
    debounce,
    getKeyboardDir
} from './../utils';
import {
    createTemplateAutocompleteLi,
} from './../core/template';
/**
 * 下拉框字段类
 */
export default class Autocomplete extends Field {
    constructor(options) {
        super(options);
        this.items = [];
        this.listCount = -1;
        this.shieldKeys = ['top', 'bottom', 'ok'];
        this.disabled = options.disabled;
        this.querySearch = options.querySearch;
        this.placeholder = options.placeholder || '';
        // this.pressKeySwitch = options.pressKeySwitch;
        if (options.validate) this.validate = new Validator(this, options);
    }
    // 事件绑定
    bindEvent() {
        // 监听box下input
        this.inputEl = this.$el.children('input').get(0);
        this.keyupHandle = debounce((e) => this.keyupProcessing(e), 300);
        this.inputEl.addEventListener('keyup', this.keyupHandle);
        // 监听box
        this.autocompleteEl = this.$el.get(0);
        this.mouseenterHandle = (e) => {
            if (this.disabled) return;
            this.value && this.$el.children('div').addClass('clear').removeClass('triangle')
        };
        this.mouseleaveHandle = (e) => this.value && this.$el.children('div').addClass('triangle').removeClass('clear');
        this.autocompleteEl.addEventListener('mouseenter', this.mouseenterHandle);
        this.autocompleteEl.addEventListener('mouseleave', this.mouseleaveHandle);
    }
    // 解除事件
    removeEvent() {
        this.autocompleteEl.removeEventListener('mouseenter', this.mouseenterHandle);
        this.autocompleteEl.removeEventListener('mouseleave', this.mouseleaveHandle);
        this.inputEl.removeEventListener('keyup', this.keyupHandle);
    }
    // 事件处理
    eventProcessing(type, element) {
        this[type + 'Processing'](element);
    }
    // 清除处理
    clearProcessing(element) {
        this.checkProcessing(element);
        this.$el.children('div').addClass('triangle').removeClass('clear');
    }
    // select选择处理
    selectProcessing(eventType, inputValue) {
        const $autocompleteBox = this.table.$autocompleteBox;
        const $loading = $autocompleteBox && $autocompleteBox.find('.loading');
        if (eventType === 'keyup') {
            if (inputValue == this.value) return;
        } 
        if (eventType === 'click') {
            const { left: boxLeft, top: boxTop } = this.table.$container.offset();
            const { left, top, height } = this.$el.offset();
            const tableBodyEl = this.table.$tableBody.get(0);
            const { scrollLeft, scrollTop } = tableBodyEl;
            const leftValue = left - boxLeft;
            const topValue = top - boxTop + height;
            this.table.autocomplePoint.left = leftValue;
            this.table.autocomplePoint.top = topValue;
            this.table.autocomplePoint.curScrollLeft = scrollLeft;
            this.table.autocomplePoint.curScrollTop = scrollTop;
            $autocompleteBox.css({ left: leftValue, top: topValue });
        }
        this.listVisible = true;
        this.$el.addClass('active');
        $loading.addClass('active');
        $autocompleteBox.show();
        $autocompleteBox.find('ul').empty();
        this.querySearch(inputValue, (dataList = []) => {
            let lis = '';
            if (dataList.length > 0) {
                dataList.forEach(value => {
                    lis += createTemplateAutocompleteLi(value);
                })
                $autocompleteBox.find('ul').html(lis);
            } else {
                this.closeAutocompleteList();
            }
            this.items = dataList;
            $loading.removeClass('active');
        }, this);
    }
    // 点击处理
    clickProcessing() {
        if (this.disabled) return;
        this.detectionSelectBox();
        const inputValue = this.inputEl.value.trim();
        const prevAutocomple = this.table.currentAutocomple;
        if (prevAutocomple && prevAutocomple != this) {
            prevAutocomple.closeAutocompleteList();
        }
        if (this.listVisible) {
            this.closeAutocompleteList();
        } else {
            this.selectProcessing('click', inputValue);
        }
        this.table.currentAutocomple = this;
    }
    // 按键处理
    keyupProcessing(event) {
        const direction = getKeyboardDir(event);
        const $autocompleteBox = this.table.$autocompleteBox;
        if (!$autocompleteBox || this.shieldKeys.indexOf(direction) >= 0) return;
        const inputValue = event.target.value.trim();
        const { rowIndex, prop, value: oldValue } = this;
        // 下拉处理
        this.selectProcessing('keyup', inputValue);
        // 实例值更新
        this.value = inputValue;
        // 数据更新
        this.table.data[rowIndex][prop] = inputValue;
        // dom属性更新
        this.inputEl.setAttribute('placeholder', inputValue || this.placeholder);
        // 触发全局事件钩子
        this.table.event.onFieldChange(rowIndex, prop, oldValue, inputValue);
    }
    // 选中处理
    checkProcessing(element) {
        const { rowIndex, prop, value: oldValue } = this;
        const newValue = element.innerText;
        // 实例值更新
        this.value = newValue;
        // 数据更新
        this.table.data[rowIndex][prop] = newValue;
        // dom值更新
        this.inputEl.value = newValue;
        // dom属性更新
        this.inputEl.setAttribute('placeholder', newValue || this.placeholder);
        // 关闭下拉
        this.closeAutocompleteList();
        // 触发全局事件钩子
        this.table.event.onFieldChange(rowIndex, prop, oldValue, newValue);
    }
    // 设置单项数据
    setSpecifiedItem(newValue) {
        const { rowIndex, prop } = this;
        // 更新当前字段数值
        this.value = newValue;
        // 更新dom值
        this.inputEl.value = newValue;
        // 更新dom属性
        this.inputEl.setAttribute('placeholder', newValue || this.placeholder);
        // 更新data数据值
        this.table.data[rowIndex][prop] = newValue;
    }
    // 关闭下拉列表
    closeAutocompleteList() {
        const $autocompleteBox = this.table.$autocompleteBox;
        const $loading = $autocompleteBox && $autocompleteBox.find('.loading');
        $autocompleteBox && $autocompleteBox.hide().find('ul').empty();
        $loading && $loading.removeClass('active');
        this.$el.removeClass('active');
        this.listVisible = false;
        this.listCount = -1;
        this.validateAction();
        return this;
    }
    // 验证动作
    validateAction() {
        this.validate && this.validate.verification(this.value).catch(() => { });
    }
    // 生成验证
    generateValidateWarn(message) {
        const spanEl = this.$el.children('span').get(0);
        spanEl.innerText = message;
        message ? $(this.inputEl).addClass('border') : $(this.inputEl).removeClass('border');
    }
}